
/*
 * =====================================================================================
 *
 *       Filename:  SessionCache.h
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  03/06/19 15:59:04
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  liushuyong (), shuyong1999@163.com
 *        Company:  shuyong
 *
 * =====================================================================================
 */

#ifndef SessionCache_H__
#define SessionCache_H__

#include "CommHead.h"
#include "RequestSession.h"
#include "Lock.h"

#include <iostream>
#include <string>
#include <unordered_map>
#include <atomic>

static const int ZONE_NUM = 20;
using std::string;
using std::pair;
using std::unordered_map;
using std::atomic;
using std::endl;

//[ key:reqid   value->[key:RequestSessionSPtr  value:time] ]
typedef unordered_map < string, pair < RequestSessionSPtr, int64_t >> SessionMap;

class SessionCache {
  public:
    SessionCache();
    ~SessionCache();
    static SessionCache* getInstance();

    RequestSessionSPtr attachSession(HttpParamSPtr param, int& err_no, bool& isNew);
    int32_t delSession(const string& reqid);
    static void cleanProc(void* arg);   //定时任务

  private:
    int32_t getZoneIndex(const string& reqid);
    void registeTimer();
    void deleteTimer();
    int32_t clean();

  private:
    SessionMap mSessZones[ZONE_NUM];    // 将reqID进行初步的分组，人为降低锁粒度
    RWLock mZoneLock[ZONE_NUM]; // lock
    bthread_timer_t mTimerID;   // sched_clean timer
    MutexLock mTimerMutex;  // timer lock
    atomic < uint32_t > mSessionCount;  // 进行原子性封装
    static SessionCache* mgpInstance;
};

#endif
